package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.changgou.canal.utils.CanalUtil;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;

@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsUpdate(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){
        System.out.println("商品信息发生改变");

        //获取修改信息
        Map<String, String> beforeMap = CanalUtil.convertToMap(rowData.getBeforeColumnsList());
        Map<String, String> aftereMap = CanalUtil.convertToMap(rowData.getAfterColumnsList());

        //商品上架信息
        String beforeMarketable = beforeMap.get("is_marketable");
        String afterMarketable = aftereMap.get("is_marketable");

        //获取最新上架的商品 0->1
        if ("0".equals(beforeMarketable) && "1".equals(afterMarketable)){
            //发送信息到商品上架交换机
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",aftereMap.get("id"));
        }

        if ("1".equals(beforeMarketable) && "0".equals(afterMarketable)){
            //发送信息到商品下架交换机
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",aftereMap.get("id"));
        }

        //商品审核信息
        String beforeStatus = beforeMap.get("status");
        String afterStatus = aftereMap.get("status");
        //获取最新审核的商品 0->1
        if ("0".equals(beforeStatus) && "1".equals(afterStatus)){
            //发送信息到商品下架交换机
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",aftereMap.get("id"));
        }

    }
}
